// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.datainterface.service.DatainterfaceService;
import com.fowo.api.datainterface.util.JsonUtil;
import com.fowo.api.entity.NavLogisticsChannel;
import com.fowo.api.model.nav.logistics.channel.NavLogisticsChannelSyncAction;
import com.fowo.api.model.nav.logistics.provider.NavLogisticsProviderVo;
import com.fowo.api.service.NavLogisticsProviderService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.user.model.JwtUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 物流管理-API对接物流-渠道基本信息 服务实现类
 *
 * @author 蜂窝蜜造平台 配置人：任凯
 */
@Service
@Slf4j
@DS("ds24")
public class NavLogisticsChannelServiceImpl extends NavLogisticsChannelBaseServiceImpl {
    //接口
    private static final String CHANNEL_CODE_PREFIX = "EC00486";


    public String getType() {
        return "EBO";
    }

    /**
     * 同步
     */
    @DataActivity(
            action = SysDataActivityAction.Other,
            message = "%s执行了同步操作"
    )
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    @Override
    public void sync(Long id) throws Exception {
        Assert.isTrue(ObjUtil.isNotEmpty(id), "参数异常!");
        try {
            NavLogisticsProviderVo voById = SpringUtil.getBean(NavLogisticsProviderService.class).getVoById(id);
            Assert.isTrue(ObjUtil.isNotEmpty(voById), "物流商不存在!");
            Assert.isTrue(StrUtil.equalsIgnoreCase(voById.getName(), this.getType()), "该物流商暂不支持同步渠道!");
            //调用接口获取数据
            Object res = SpringUtil.getBean(DatainterfaceService.class).executeInterface(null, CHANNEL_CODE_PREFIX, null, null, null);
            //断言接口返回结果不为空
            Assert.isTrue(ObjUtil.isAllNotEmpty(res), "同步服务器返回结果为空!");
            //将返回结果转换为JSONObject
            JSONObject obj = Convert.convertQuietly(JSONObject.class, res);
            //断言接口返回状态码为0
            Assert.isTrue(StrUtil.equalsIgnoreCase("0", MapUtil.getStr(obj, "Code")), "同步服务器返回错误状态码错误!");
            //获取远程列表
            JSONArray remoteList = JsonUtil.getJsonToJsonArraySafe(obj, "$.Items.ExpressItem");
            //获取本地列表
            List<NavLogisticsChannel> dbList = list(Wrappers.<NavLogisticsChannel>lambdaQuery().eq(NavLogisticsChannel::getNavLogisticsProviderId, id));
            //遍历远程列表
            for (JSONObject item : JsonUtil.getJsonToList(remoteList)) {
                //查找本地列表中是否存在
                Optional<NavLogisticsChannel> entityOptional = dbList.stream().filter(a -> StrUtil.equals(MapUtil.getStr(item, "ExpressId"), a.getExpressId())).findFirst();
                //如果存在
                if (entityOptional.isPresent()) {
                    NavLogisticsChannel entity = entityOptional.get();
                    //更新本地列表
                    entity.setExpressId(MapUtil.getStr(item, "ExpressId"));
                    entity.setExpressName(MapUtil.getStr(item, "ExpressName"));
                    entity.setProviderName(voById.getName());
                    //获取当前用户
                    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
                    //如果存在当前用户
                    if (currentUser != null) {
                        entity.setLastUpdateUser(currentUser.getUserId());
                    }
                    entity.setLastUpdateTime(new Date());
                } else {
                    //如果不存在
                    NavLogisticsChannel entity = new NavLogisticsChannel();
                    entity.setExpressId(MapUtil.getStr(item, "ExpressId"));
                    entity.setExpressName(MapUtil.getStr(item, "ExpressName"));
                    entity.setNavLogisticsProviderId(id);
                    //获取当前用户
                    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
                    entity.setCreateTime(new Date());
                    entity.setLastUpdateTime(new Date());
                    //如果存在当前用户
                    if (currentUser != null) {
                        entity.setCreateUser(currentUser.getUserId());
                        entity.setLastUpdateUser(currentUser.getUserId());
                    }
                    //添加到本地列表
                    dbList.add(entity);
                }
            }
            //保存或更新本地列表
            saveOrUpdateBatch(dbList);
        } catch (Exception ex) {
            log.error("同步EBO渠道错误,异常信息:" + StrUtil.subPre(ExceptionUtil.getRootCauseMessage(ex), 2000));
            throw new RuntimeException("审核发生异常,信息:" + StrUtil.subPre(ExceptionUtil.getRootCauseMessage(ex), 2000));
        }
    }
}






